#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    connect(ui->pushButtonselect,SIGNAL(clicked()),this,SLOT(btnselectSlot()));
    udpsocket=new QUdpSocket(this);
    socket=new QTcpSocket(this);
    socket_json=new QTcpSocket(this);
    timer = new QTimer(this);
    connect(ui->pushButtonconnect,SIGNAL(clicked()),this,SLOT(btnconnectSlot()));
}

Dialog::~Dialog()
{
    delete ui;
    if(socket->isOpen())
    {
        socket->close();
    }
}

QString Dialog::inJSON(QByteArray byteArray)
{
    //解析JSON
    QString strName;
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(byteArray, &jsonError);
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
    {
        if (doucment.isObject())
        {
            QJsonObject object = doucment.object();
            if (object.contains("up_config"))
            {
                QJsonValue value = object.value("up_config");
                if (value.isString())
                {
                    strName = value.toString();
                    qDebug() << strName;
                }
            }
        }
    }
    return strName;
}

void Dialog::putJson()
{
    //发送开始信息
    QJsonObject json_start;
    json_start.insert("type",2);
    QJsonObject dataobject_start;
    dataobject_start.insert("flag","start");
    dataobject_start.insert("file_name","config.json");
    dataobject_start.insert("file_len","2048");
    json_start.insert("data", QJsonValue(dataobject_start));
    // 构建 Json 文档
    QJsonDocument document_start;
    document_start.setObject(json_start);
    QByteArray byteArray_start = document_start.toJson(QJsonDocument::Compact);
    QString jtext_start(byteArray_start);
    socket->write(byteArray_start);
    qDebug()<<jtext_start;

    //建立下发点表的连接
    socket_json->connectToHost(sender.toString(),8878);
    connect(socket_json,SIGNAL(connected()),this,SLOT(fileconnectSlot()));
    //发送结束信息
    QJsonObject json_stop;
    json_stop.insert("type",2);
    QJsonObject dataobject_stop;
    dataobject_stop.insert("flag","stop");
    dataobject_stop.insert("file_name","config.json");
    dataobject_stop.insert("file_len","2048");
    json_stop.insert("data", QJsonValue(dataobject_stop));
    // 构建 Json 文档
    QJsonDocument document_stop;
    document_stop.setObject(json_stop);
    QByteArray byteArray_stop = document_stop.toJson(QJsonDocument::Compact);
    QString jtext_stop(byteArray_stop);
    socket->write(byteArray_stop);
    qDebug()<<jtext_stop;

    timer->setInterval(5000);
    timer->setSingleShot(false);
    connect(timer,SIGNAL(timeout()),this,SLOT(timeOutSlot()));
    timer->start();
}

void Dialog::btnselectSlot()
{
    QByteArray text="114514";
    QHostAddress broadaddr("192.168.31.255");
    int port=8886;
    udpsocket->writeDatagram(text,broadaddr,port);
    connect(udpsocket,SIGNAL(readyRead()),this,SLOT(readReadySlot()));
}

void Dialog::btnconnectSlot()
{
    QMessageBox::information(this,"information","连接设备成功");
    socket->connectToHost(sender.toString(),senderPort);

    connect(socket,SIGNAL(connected()),this,SLOT(connectSlot()));
}

void Dialog::readReadySlot()
{

    datagram.resize(udpsocket->pendingDatagramSize());

    // 接收数据
    udpsocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
    qDebug() << "Received message from " << sender.toString() << ":" << senderPort << " : " << datagram.data();
    QString ip=sender.toString().append(":%1");
    ui->lineEdit->setText(ip.arg(senderPort));
}

void Dialog::connectSlot()
{
    QJsonObject json;
    json.insert("type",1);
    // 构建 Json 文档
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString jtext(byteArray);
    socket->write(byteArray);
    qDebug()<<jtext;
    connect(socket,SIGNAL(readyRead()),this,SLOT(TCPreadReadySlot()));


}

void Dialog::TCPreadReadySlot()
{
    QByteArray byteArray = socket->readAll();
    QString file=inJSON(byteArray);
    QString trues="true";
    int refult=file.compare(trues);
    if(refult==0)
    {
        qDebug()<<"文件不存在";
        putJson();//下发JSON文件
    }

}

void Dialog::timeOutSlot()
{
    QJsonObject json;
    json.insert("type",3);
    // 构建 Json 文档
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString jtext(byteArray);
    socket->write(byteArray);
    qDebug()<<jtext;
}

void Dialog::fileconnectSlot()
{
    QString array;
    readPath="C:/Users/lenovo/Desktop/project/edge-computing/config/config.json";
    QFile readFile(readPath);
    readFile.open(QIODevice::ReadOnly);
    while(!readFile.atEnd())    // 判断是否读到文件尾部
    {
        array = readFile.read(2048);    // 每次读取2kb
        QByteArray bytearray=array.toUtf8();
        socket_json->write(bytearray);
        QString text(bytearray);
        qDebug()<<text;
    }
    qDebug()<<"chuanshu wancheng";
}
